module.exports = function($scope, $modal, $modalInstance, $resource, activities, userinfo, date2str, toaster){

    $scope.activities = activities.slice(1);
    $scope.item = {
        'tour_date': date2str(new Date()),
        'opened': false
    }
    
    $resource('/api/as/sc/office/getForGovList', {}, {}).save({'company_id': userinfo.company_id}, function (res) {
        if (res.errcode === 0){
            $scope.company_list = res.data;
            $scope.company_list.push({
                id: userinfo.id,
                code: userinfo.company_code,
                name: userinfo.name
            })
        } else {
            toaster.error({title: '', body: '查询机构列表, 请刷新页面'});
        }
    });

    $scope.ok = function() {
        var para = check($scope.item);
        if(para == 0){
            return;
        }
        $resource('/api/ac/ggc/voluntourismAccountService/addAccountList', {}, {}).save(para, function (res) {
            if (res.errcode === 0){
                toaster.success({title: '', body: '添加成功'});
                $modalInstance.close(para);
            } else {
                toaster.error({title: '', body: res.errmsg});
            }
        });
    }

    function check(item){
        var para = {};
        if(!item.company){
            toaster.warning({title: '', body: '请选择机构'});
            return 0;
        }
        para.company_name = item.company.name;
        para.company_code = item.company.code;

        if(!item.activity){
            toaster.warning({title: '', body: '请选择参加的活动'});
            return 0;
        }
        if(!item.tour_stock || item.tour_stock < 0){
            toaster.warning({title: '', body: '参加的人数错误'});
            return 0;
        }
        if(item.tour_stock > item.activity.stock){
            toaster.warning({title: '', body: '已超过活动剩余库存'});
            return 0;
        }
        para.activity_id = item.activity.id;
        para.tour_stock = item.tour_stock;
        para.tour_date = date2str(item.tour_date);

        return para;
    }

    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    }

    //打开日历空间,选择时间
    $scope.dateOpen = function($event, item){
        $event.preventDefault();
        $event.stopPropagation();
        item.opened = true;
    }

};